package com.eeepay.eeepay_v2.activity;

import android.graphics.Color;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.ColorUitls;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.MathUtils;
import com.eeepay.eeepay_v2.view.LegendView;
import com.eeepay.v2_library.ui.ABBaseActivity;

import java.util.ArrayList;
import java.util.List;

import cn.eeepay.api.grpc.nano.TransApiServiceGrpc;
import cn.eeepay.api.grpc.nano.TransProto;
import io.grpc.ManagedChannel;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.view.PieChartView;

import static com.eeepay.eeepay_v2.util.ColorUitls.colors;

/**
 * Created by zw on 2016/4/26 0026.
 * 单日交易详情
 */
public class OneDayTradeDetailActivity extends ABBaseActivity implements View.OnClickListener {
    private final int SINGLE = 1, AMOUNT = 2;
    private TextView tv_tradeTransaction, tv_tradeNumber;
    private TextView tv_title, tv_unit;
//    private PieChart pieChartAmount, pieChartSingle;//饼图

    private PieChartView pieChartAmount, pieChartSingle;//饼图2
    private LinearLayout lLayout_legend;
    private LegendView[] legends;//说明文字

    private String date;

    private int singleTotal;//交易总笔数
    private float amountTotal; //交易总金额
    private TransProto.DayTransInfo[] dayTransInfo;//交易详细数据

    @Override
    protected int getLayoutId() {
        return R.layout.activity_one_day_trade_tedail;
    }

    @Override
    protected void initWidget() {
        if (bundle != null) {
            date = bundle.getString("date");
        }
        tv_tradeTransaction = getViewById(R.id.tv_trade_transaction);
        tv_tradeNumber = getViewById(R.id.tv_trade_number);

        tv_title = getViewById(R.id.tv_content_title);
        tv_unit = getViewById(R.id.tv_unit);

        pieChartAmount = getViewById(R.id.pie_chart_amount);
        pieChartSingle = getViewById(R.id.pie_chart_single);

        lLayout_legend = getViewById(R.id.layout_legend);
        sendHttpRequest(0);

    }

    /**
     * 初始化饼状图
     */
    private void initPieChart(PieChartView pieChartView, List<SliceValue> values) {
        PieChartData pieChardata = new PieChartData();
        pieChardata.setHasLabels(false);//显示表情
        pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
        pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
        pieChardata.setHasCenterCircle(true);//是否是环形显示
        pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
        pieChardata.setCenterCircleScale(0.5f);//设置环形的大小级别
//        pieChardata.setCenterText1("饼图测试");//环形中间的文字1
        pieChardata.setCenterText1Color(Color.BLACK);//文字颜色
        pieChardata.setCenterText1FontSize(14);//文字大小

//        pieChardata.setCenterText2("饼图测试");
        pieChardata.setCenterText2Color(Color.BLACK);
        pieChardata.setCenterText2FontSize(14);
        /**这里也可以自定义你的字体   Roboto-Italic.ttf这个就是你的字体库*/
//      Typeface tf = Typeface.createFromAsset(this.getAssets(), "Roboto-Italic.ttf");
//      data.setCenterText1Typeface(tf);
        pieChartView.setValueSelectionEnabled(false);//选择饼图某一块变大
        pieChartView.setAlpha(0.9f);//设置透明度
        pieChartView.setCircleFillRatio(1f);//设置饼图大小

        pieChardata.setValues(values);//填充数据
        pieChartView.setPieChartData(pieChardata);
    }


    /**
     * 设置饼状图的数据
     */
    private void setPieData(int flag) {
        getPieData(flag);
        //说明文字
        switch (flag) {
            case SINGLE://交易笔数
                tv_title.setText(date + "产品交易笔数");
                tv_unit.setText("单位:笔");
//                pieChartSingle.setCenterText("总数\n" + singleTotal + "笔");//中间的文字
                pieChartSingle.getPieChartData().setCenterText1("总数");
                pieChartSingle.getPieChartData().setCenterText2(singleTotal + "笔");
                pieChartSingle.setVisibility(View.VISIBLE);
                pieChartAmount.setVisibility(View.GONE);
                break;
            case AMOUNT://交易金额
                tv_title.setText(date + "产品交易金额");
                tv_unit.setText("单位:元");
//                pieChartAmount.setCenterText("总数\n" + amountTotal + "元");//中间的文字
                pieChartAmount.getPieChartData().setCenterText1("总数");//中间的文字
                pieChartAmount.getPieChartData().setCenterText2(amountTotal + "元");
                pieChartSingle.setVisibility(View.GONE);
                pieChartAmount.setVisibility(View.VISIBLE);
                break;
        }
        if (dayTransInfo != null && dayTransInfo.length > 0)
            legends = new LegendView[dayTransInfo.length];
        lLayout_legend.removeAllViews();
        for (int i = 0; i < dayTransInfo.length; i++) {
            if (legends[i] == null) {
                legends[i] = new LegendView(mContext);
                int parseColor;
                if (i > colors.length - 1) {
                    //add by zhuangzeqin 2017年8月29日14:28:08 如果业务产品超过定义的颜色数组的长度；就生成随机颜色-- 避免由于数组的长度变化；导致数组越界
                    parseColor = Color.parseColor(ColorUitls.getColorByRandom());
                } else {
                    parseColor = Color.parseColor(colors[i]);//否则直接用定义的颜色数组的颜色值
                }
//                legends[i].setImageColor(Color.parseColor(colors[i]));//说明文字
                legends[i].setImageColor(parseColor);//说明文字
            }
            legends[i].setName(dayTransInfo[i].bpName);
            String str = (flag == AMOUNT ? (dayTransInfo[i].proAmountTotal + "元") :
                    (dayTransInfo[i].proSingleTotal + "笔"));
            legends[i].setCount(str);
            lLayout_legend.addView(legends[i]);
        }
    }


    @Override
    protected void eventOnClick() {
        tv_tradeTransaction.setOnClickListener(this);
        tv_tradeNumber.setOnClickListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void getPieData(int flag) {
        /**
         * 将一个饼形图分成 N 部分，
         */
        List<SliceValue> values = new ArrayList<SliceValue>();//饼图数据的封装
        float[] quarterly = new float[dayTransInfo.length];
        for (int i = 0; i < dayTransInfo.length; i++) {
            switch (flag) {
                case SINGLE:
                    quarterly[i] = MathUtils.String2Float(dayTransInfo[i].proSingleTotal);
                    break;
                case AMOUNT:
                    quarterly[i] = MathUtils.String2Float(dayTransInfo[i].proAmountTotal);
                    break;
            }
            int parseColor;
            if (i > ColorUitls.colors.length - 1) {
                //add by zhuangzeqin 2017年8月29日14:28:08 如果业务产品超过定义的颜色数组的长度；就生成随机颜色-- 避免由于数组的长度变化；导致数组越界
                parseColor = Color.parseColor(ColorUitls.getColorByRandom());
            } else {
                parseColor = Color.parseColor(ColorUitls.colors[i]);//否则直接用定义的颜色数组的颜色值
            }
            SliceValue sliceValue = new SliceValue(quarterly[i], parseColor);
            values.add(sliceValue);
        }
        if (flag == SINGLE)
            initPieChart(pieChartSingle, values);
        else if (flag == AMOUNT)
            initPieChart(pieChartAmount, values);
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {

                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        TransApiServiceGrpc.TransApiServiceBlockingStub stub = TransApiServiceGrpc.newBlockingStub(channel);
                        TransProto.ReqTrans request = new TransProto.ReqTrans();
                        request.agentNo = UserInfo.getUserInfo2SP().getAgentNo();
                        request.transDate = date;
                        TransProto.DayTransRes response = stub.getDayTrans(request);
                        return response;
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        if (result == null) {
                            showToast("查询失败");
                            return;
                        }
                        TransProto.DayTransRes response = (TransProto.DayTransRes) result;
                        if (!response.resMsg.status) {
                            showToast(response.resMsg.msg);
                            return;
                        }
                        amountTotal = MathUtils.String2Float(response.amountTotal);
                        singleTotal = MathUtils.String2Int(response.singleTotal);
                        dayTransInfo = response.dayTransInfo;
                        //饼状图数据
                        setPieData(AMOUNT);

                    }
                });
    }

    @Override
    public void onClick(View v) {
        v.setEnabled(false);
        switch (v.getId()) {
            case R.id.tv_trade_transaction:
                tv_tradeNumber.setEnabled(true);
                setPieData(AMOUNT);
                break;
            case R.id.tv_trade_number:
                tv_tradeTransaction.setEnabled(true);
                setPieData(SINGLE);
                break;
        }
    }

}
